package edu.ccut.saturn.studio.core.util.eclipse;

import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.ui.plugin.AbstractUIPlugin;

public class SaturnDialogSettings {

	private AbstractUIPlugin activator = null;

	public SaturnDialogSettings(AbstractUIPlugin activator) {
		this.activator = activator;
	}

	public IDialogSettings getDialogSettings(String section) {
		IDialogSettings dialogsettings = this.activator.getDialogSettings();

		IDialogSettings connectionDialogsettings = dialogsettings
				.getSection(section);

		if (connectionDialogsettings == null) {
			connectionDialogsettings = dialogsettings.addNewSection(section);
		}

		return connectionDialogsettings;
	}

	public String[] getHistory(String section, String key) {
		return getDialogSettings(section).getArray(key);
	}

	public void addHistory(String section, String key, String value) {
		String[] history = getHistory(section, key);

		if (!this.hasHistory(history, value)) {
			getDialogSettings(section).put(key, getHistory(history, value));
		}
	}

	private String[] getHistory(String[] history, String str) {
		String[] newHistory = null;

		if (history == null) {
			return new String[] {str};
		}
		
		if (history.length == 10) {
			newHistory = history;
		} else {
			newHistory = new String[history.length + 1];
		}

		System.arraycopy(history, 0, newHistory, 1, newHistory.length - 1);
		newHistory[0] = str;

		return newHistory;
	}

	private boolean hasHistory(String[] historys, String value) {
		if (historys != null) {
			for (String history : historys) {
				if (history.equals(value)) {
					return true;
				}
			}
		}

		return false;
	}
}
